const bodyParser = require("body-parser");
const cors = require("cors");
const { logger } = require("./config/logger");
const helmet = require("helmet");
const createIO = require("./socket");
const path = require("path")
require("dotenv").config({ path: path.resolve(__dirname, './.env') });
const { buildErrObject } = require("./utils/buildErrObject");

/** Connect to MongoDB */
const mongoose = require("mongoose");
require("./config/db");

// server.js
const express = require("express"); // 引入express
const app = express(); // express初始化

//log4js 日志中间件格式
//正式环境应该把JSON.stringify(req.body)这个去掉，这个是记录每个请求的参数，正式环境应该不能记录用户的操作
app.use(logger.connectLogger(logger.getLogger("info"), {
    level: logger.levels.DEBUG,
    format: (req, res, format) => format(`:remote-addr :method :url :status :response-timems ${JSON.stringify(req.body)} :referrer HTTP/:http-version :user-agent`),
}));

app.all("*", function (req, res, next) {
    // 写入相应的拦截操作
    next(); // 要继续往下跑记得写上 next()
});

// Configure middlewares
app.use(cors());
app.use(bodyParser.json());
app.use(helmet());

// 引入JWT中间件
app.use(require("./plugins/expressJwt"));

app.use((err, req, res, next) => {
    if (err.name === "UnauthorizedError") {
        res.status(401).send(buildErrObject(401, "用户登录已过期或无访问权限"));
    }
});

// router
app.use("/api", require("./routes/api"));

// 最终匹配不到的路由，返回404 NotFound
app.use("*", function (req, res) {
    res.header("Content-Type", "text/html;charset=utf-8");
    res.status(404).send('<h1 style="text-align: center;">Not Found</h1>');
});

const server = createIO(app);
const port = process.env.PORT || 5000; // 设置端口号
server.listen(port, () => {
    //启动服务,监听端口
    console.log(`Server is Running on http://localhost:${port}`);
});
